import {messages} from "share/common";
import React, { Component, PropTypes } from 'react';
import { Popover, Icon, Button, Input, Popconfirm } from 'antd'
import 'styles/components/template/annotate.scss'
import HoverContent from 'components/hover-content'
import financeAuditService from 'containers/financial-management/new-finance-audit/finance-audit.service'
import SVGIcon from "components/SVGIcon";
const TextArea = Input.TextArea;

class Annotate extends Component {

  state = {
    popoverVisible: false,
    text: '',
    loading: false,
    deleting: []
  };　

  getPopupContainer = triggerNode => triggerNode.parentNode;

  addAnnotate = () => {
    const { text } = this.state;
    const { params, onAdd, onChange } = this.props;
    if(params) {
      this.setState({ loading: true });
      params.target && typeof params.target === 'object' && (params.target = JSON.stringify(params.target));
      financeAuditService.addAnnotate({ text, ...params })
        .then(res => {
          onChange();
          this.setState({ text: '', popoverVisible: false  })
        })
        .finally(() => {
          this.setState({ loading: false });
        })
    } else {
      onAdd(text);
      this.setState({ text: '', popoverVisible: false })
    }
  };

  deleteAnnotate = (index, id) => {
    const { params, onDelete, onChange } = this.props;
    const { deleting } = this.state;
    if(params) {
      deleting.push(id);
      this.setState({ deleting });
      financeAuditService.deleteAnnotate(id)
        .then(res => {
          onChange();
        })
        .finally(() => {
          deleting.delete(id);
          this.setState({ deleting });
        })
    } else {
      onDelete(index)
    }
  };

  getPopoverContent = () => {
    const { text, loading } = this.state;
    return <div className='annotate-popover'>
      <TextArea
        rows={4}
        value={text}
        onChange={e => this.setState({ text: e.target.value })}
        placeholder={messages('common-1.key177')/*请输入批注内容*/}
      />
      <div className='annotate-popover-buttons'>
        <Button onClick={this.toState({ popoverVisible: false })}>{messages('common.cancel')/*取消*/}</Button>
        <Button onClick={this.addAnnotate} type='primary' disabled={!text} loading={loading}>{messages('common.ok')/*确定*/}</Button>
      </div>
    </div>
  };

  getContent = () => {
    const { popoverVisible } = this.state;
    return  <Popover
      getPopupContainer={this.getPopupContainer}
      visible={popoverVisible}
      content={this.getPopoverContent()}
      trigger="click"
      placement='bottomRight'
      onVisibleChange={popoverVisible => this.setState({ popoverVisible })}
    >
      <div className='annotate-wrapper-content' onClick={this.toState({ popoverVisible: true })}>
        <SVGIcon type="annotate" className='annotate-icon'/>
      </div>
    </Popover>
  };

  getAnnotateContent = () => {
    const { annotateList, mode, disabled } = this.props;
    const { deleting } = this.state;
    return <div className={this.classNames(['annotate-list', { 'pop-down': mode !== 'hover' }])}>
      {annotateList.sort((a, b) => new Date(b.createdDate) - new Date(a.createdDate))
        .map((annotate, index) => <HoverContent
          key={annotate.id}
          disabled={disabled || annotate.disabled}
          placement={{
            left: childrenRect => childrenRect.width - 24,
            top: childrenRect => childrenRect.height / 2 - 12
          }}
          wrapperClassName='annotate-list-item-wrapper'
          content={<Popconfirm
            title={messages('common-1.key178')/*确定要删除这条批注吗?*/}
            overlayStyle={{ width: 200 }}
            placement="topRight"
            autoAdjustOverflow={false}
            onConfirm={() => this.deleteAnnotate(index, annotate.id)}
            getPopupContainer={this.getPopupContainer}
          >
            <Icon type={deleting.find(id => id === annotate.id) ? 'loading' : 'delete'} style={{ color: '#FF9C53' }}/>
          </Popconfirm>}
        >
        <div className='annotate-list-item'>
          <div className='annotate-list-item-title'>
            {new Date(annotate.createdDate).format('yyyy-MM-dd hh:mm')}
          </div>
          <div className='annotate-list-item-content'>{annotate.createdByUserName}：{annotate.text}</div>
        </div>
      </HoverContent>)}
    </div>
  };

  render() {
    const { children, validStyle, annotateList, mode, disabled, iconStyle } = this.props;
    let annotateListPopoverVisibleProps = annotateList.length === 0 ? {
      visible: false
    } : {};
    let child = React.isValidElement(children) ? children : React.createElement('span', null, children);
    let childProps = child.props || {};
    return mode === 'hover' ? (
      <HoverContent
        placement={{
          left: childrenRect => childrenRect.width - 24,
          top: childrenRect => childrenRect.height / 2 - 12
        }}
        content={this.getContent()}
        wrapperClassName='annotate-wrapper'
        onVisibleChange={this.toState({ popoverVisible: false })}
        disabled={disabled}
      >
        <Popover
          getPopupContainer={this.getPopupContainer}
          content={this.getAnnotateContent()}
          placement='bottomLeft'
          {...annotateListPopoverVisibleProps}
        >
          {React.cloneElement(
            child,
            {
              style: Object.assign({}, childProps.style, annotateList.length > 0 ? validStyle : {})
            }
          )}
        </Popover>
      </HoverContent>
    ) : (
      <div>
        <HoverContent
          placement={{
            left: childrenRect => childrenRect.width - 24,
            top: childrenRect => childrenRect.height / 2 - 12
          }}
          content={this.getContent()}
          wrapperClassName='annotate-wrapper'
          onVisibleChange={this.toState({ popoverVisible: false })}
          disabled={disabled}
          iconStyle={iconStyle}
          getPopupContainer={triggerNode => triggerNode}
        >
          {React.cloneElement(
            child,
            {
              style: Object.assign({}, childProps.style, annotateList.length > 0 ? validStyle : {})
            }
          )}
        </HoverContent>
        {annotateList.length > 0 && this.getAnnotateContent()}
      </div>
    )
  }

  static propTypes = {
    validStyle: PropTypes.object,
    annotateList: PropTypes.array,
    mode: PropTypes.string,
    onAdd: PropTypes.func,
    onDelete: PropTypes.func,
    onChange: PropTypes.func,
    disabled: PropTypes.bool,
    iconStyle: PropTypes.object
  };

  static defaultProps = {
    validStyle: {},
    annotateList: [],
    onAdd: () => {},
    onDelete: () => {},
    onChange: () => {}
  };

}

export default Annotate;
